package com.cn.wanix.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.wanix.model.ResultModel;
import com.cn.wanix.model.UserModel;
import com.cn.wanix.service.UserService;
import com.cn.wanix.service.impl.UserServiceImpl;
import com.cn.wanix.util.ResultTool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        1.拿到页面的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//        2.封装model
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
//        3.调用服务逻辑层
        UserService userService = new UserServiceImpl();
//        如果参数能够封装成一个对象，就必须封装

//        4.返回一个结果
        ResultModel resultModel = userService.login(userModel);
        if (resultModel.getCode().equals(ResultTool.CODE_SUCCES)) {
//四大作用域的范围?
            req.getSession().setAttribute("username", username);
        }
//        5.返回页面状态
//        PrintWriter out = resp.getWriter();
        String resJSON = JSON.toJSONString(resultModel);     // 转换为json
        resp.getWriter().print(resJSON); // 输出
    }
}
